package com.ilxqx.framework.security.handler;

import com.ilxqx.framework.security.constant.SecurityConstants;
import com.ilxqx.framework.security.po.UserDetailsImpl;
import com.ilxqx.framework.security.util.AuthUtils;
import com.ilxqx.framework.security.util.KeyUtils;
import com.ilxqx.framework.system.util.ResponseUtils;
import com.ilxqx.framework.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author venus
 * 登录成功处理类
 */
@Component
@Slf4j
public class FrameworkAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功处理逻辑
     * @param httpServletRequest request对象
     * @param httpServletResponse response对象
     * @param authentication 验证异常
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        log.info("账号[{}]登录成功，用户ID[{}]，用户登录地IP[{}]", authentication.getName(),
                ((UserDetailsImpl) authentication.getPrincipal()).getUserId(),
                ((WebAuthenticationDetails) authentication.getDetails()).getRemoteAddress());
        // 刷新一下用户权限
        if (!Objects.equals(SecurityConstants.SUPER_ADMIN_USER_ID, AuthUtils.getLoggedUserId())) {
            AuthUtils.refreshLoggedUserPermissions();
        }
        // 设置一个X-Auth-Key
        // 为登录用户分配一个key
        String userAgent = httpServletRequest.getHeader(HttpHeaders.USER_AGENT);
        String ip = httpServletRequest.getRemoteAddr();
        String key = KeyUtils.generateAccessKey(ip, userAgent);
        log.info("为账号[{}]生成访问key[{}]", authentication.getName(), key);
        httpServletResponse.setHeader("X-Access-Key", key);
        ResponseUtils.response(ResultUtils.success("登录成功", authentication.getName()), httpServletRequest, httpServletResponse);
    }

}
